import 'package:flutter/gestures.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:syria_sports/data/apiClient/apis_data.dart';
import 'package:syria_sports/data/models/auth/user.dart';
import 'package:syria_sports/presentation/admin_home_tabs/players_tab/bloc/players_tab_cubit.dart';
import 'package:syria_sports/presentation/players/add_player_page/bloc/add_player_page_screen.dart';
import 'package:syria_sports/presentation/players/add_player_page/widgets/my_circle_avatar.dart';
import 'package:syria_sports/presentation/admin_home_tabs/cp_tab/bloc/cp_cubit.dart';
import '../../../../data/controllers/player_controller.dart';
import '../../../../dialogs/add_attendance_dialog.dart';
import '../../../../dialogs/delete_player_confirmation.dart';
import '../../../players/player_profile_screen/player_profile_screen.dart';
import 'package:fluent_ui/fluent_ui.dart' as fui;


class PlayerGridItemView extends StatefulWidget {
  final User user;
  final int index;
  final PlayersTabCubit? playersTabCubit;
  final Function(bool ,User)? onSelected;
  const PlayerGridItemView({super.key, required this.user, required this.index, this.playersTabCubit, this.onSelected});

  @override
  State<PlayerGridItemView> createState() => _PlayerGridItemViewState();
}

class _PlayerGridItemViewState extends State<PlayerGridItemView> {
  late bool selected;

  @override
  void initState() {
    selected = false;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    final menuController = fui.FlyoutController();
    late LongPressDownDetails longPD ;
    return fui.FlyoutTarget(
        controller: menuController,
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PlayerProfileScreen.builder(
                  index: widget.index,
                  context: context,
                  user: widget.user,
                ),
              ),
            );
          },
          onSecondaryTapDown: (details) {
            _showContextMenu(context, details.globalPosition);
          },
          onLongPressDown: (details){
            longPD = details;
          },
          onLongPress: (){
            _showContextMenu(context, longPD.globalPosition);
          },
          child:BlocBuilder<PlayersTabCubit,PlayersTabState>(
            buildWhen: (p,c) {
              if(c is SelectAllPlayersState) {
                selected =c.value;
              }
              return c is SelectAllPlayersState;
            },
            builder:(context,state) =>Stack(
              children: [
                SizedBox(
                  width: double.maxFinite,
                  child: Card(
                    color: Theme.of(context).colorScheme.secondary,
                    child: Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Align(
                            alignment: Alignment.center,
                            child: Hero(
                              tag: "player_selected${widget.index}",
                              child: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: MyCircleAvatar(
                                  borderColor: Colors.red,
                                  editMode: false,
                                  width: 38,
                                  activeIconWidth: 22,
                                  imageURL: widget.user.image,
                                  active: widget.user.activeValue == '1',
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 8), // مسافة أفقية بين العناصر
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(widget.user.fullName, style: theme.textTheme.titleSmall,maxLines: 2,overflow: TextOverflow.ellipsis,),
                                Text("المستوى: ${widget.user.level}", style: CustomTextStyles.bodySmallOnPrimary),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                if(widget.playersTabCubit?.selectedMode == true)
                  Align(
                    alignment: Alignment.topLeft,
                    child: Checkbox(
                      value: selected,
                      onChanged: (value){
                        setState(() {
                          selected = value??false;
                          print(selected);
                          //widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
                        });
                        widget.onSelected?.call(value??false,widget.user);
                      },
                    ),
                  ),
              ],
            ),
          ),
        )
    );
  }

  void showDeleteConfirmation(BuildContext context1, User player) {
    showDialog(
      context: context1,
      builder: (BuildContext context) {
        if(widget.playersTabCubit?.selectedMode == true){
          return DeleteConfirmationDialog(
            titleUser: "(${widget.playersTabCubit!.selectedUsers.length})",
            playerName: 'لاعب',
            onConfirm: () async{
              for(User user in widget.playersTabCubit!.selectedUsers){
                widget.playersTabCubit?.add(DeletePlayerLoadingEvent());
                await PlayerController.deleteById(user.playerId??'-1').then((value){
                  if(value != null){
                    widget.playersTabCubit?.add(DeletePlayerSuccessEvent(userId: user.userId));
                    widget.playersTabCubit?.add(ChangeSelectedItem(value: false, user: user));
                  }else{
                    widget.playersTabCubit?.add(DeletePlayerFailedEvent());
                  }
                });
              }
            },
          );
        }

        return DeleteConfirmationDialog(
          titleUser: 'اللاعب',
          playerName: player.fullName,
          onConfirm: () {
            widget.playersTabCubit?.add(DeletePlayerLoadingEvent());
            PlayerController.deleteById(player.playerId??'-1').then((value){
              if(value != null){
                widget.playersTabCubit?.add(DeletePlayerSuccessEvent(userId: player.userId));
              }else{
                widget.playersTabCubit?.add(DeletePlayerFailedEvent());
              }
            });
          },
        );
      },
    );
  }

  void showAddAttendanceDialog(BuildContext context, User player) {
    if(APISData.cpCubit.state is CPLoading){
      showErrorMessage(message: 'يرجى الانتظار ريثما يتم جلب التمارين والنوادي');
      return;
    }
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AddAttendanceDialog(
          player: player,
        );
      },
    );

  }

  void _showContextMenu(BuildContext context, Offset position) async {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
    final result = await showMenu<int>(
      context: context,
      position: RelativeRect.fromLTRB(
        position.dx,
        position.dy,
        overlay.size.width - position.dx, // المسافة من اليمين
        overlay.size.height - position.dy, // المسافة من الأسفل
      ),
      items: [
        PopupMenuItem(
          height: 32,
          onTap:() {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PlayerProfileScreen.builder(
                  index: widget.index,
                  context: context,
                  user: widget.user,
                ),
              ),
            );
          },
          child: Row(
            children: [
              Icon(Icons.open_in_new_rounded,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('عرض',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap:() {
            showDeleteConfirmation(context, widget.user);
          },
          child: Row(
            children: [
              Icon(Icons.delete_outline,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              /*if(widget.playersTabCubit?.selectedMode==true)
                Text("حذف (${widget.playersTabCubit!.selectedUsers.length})",style: theme.textTheme.labelLarge,)
              else*/
                Text('حذف',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap:() {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => AddPlayerPageScreen(
                  player: widget.user,
                  playersTabCubit: widget.playersTabCubit,
                ),
              ),
            );
          },
          child: Row(
            children: [
              Icon(Icons.edit,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('تعديل',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
            setState(() {
              selected = true;
              widget.onSelected?.call(true,widget.user);
            });
          },
          child: Row(
            children: [
              Icon(Icons.check_box_outlined,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('تحديد',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            if(widget.playersTabCubit?.selectedMode == false) {
              widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
            }
            setState(() {
              selected = false;
              widget.onSelected?.call(false,widget.user);
            });
          },
          child: Row(
            children: [
              Icon(Icons.check_box_outline_blank,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('إلغاء التحديد',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
            widget.playersTabCubit?.add(TabSelectAll(value: true));
          },
          child: Row(
            children: [
              Icon(Icons.select_all,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('تحديد الكل',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            widget.playersTabCubit?.add(ChangeSelectMode(mod: false));
            widget.playersTabCubit?.add(TabSelectAll(value: false));
          },
          child: Row(
            children: [
              Icon(Icons.deselect,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('إلغاء تحديد الكل',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
      ],
    );
  }
}